package communication.server;

import game.units.Character;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import java.net.Socket;


public class CommunicationServerThread extends Thread {
	private CommunicationServer server = null;
	private Socket socket = null;
	private int ID = -1;
	private DataInputStream streamIn = null;
	private DataOutputStream streamOut = null;
	
	private Character character = null;

	protected CommunicationServerThread(CommunicationServer server, Socket socket) {
		super();
		this.server = server;
		this.socket = socket;
		ID = socket.getPort();
	}

	protected void send(String msg) {
		try {
			streamOut.writeUTF(msg);
			streamOut.flush();
		} catch (IOException ioe) {
			System.out.println(ID + " ERROR sending: " + ioe.getMessage());
			server.remove(this);
		}
	}

	protected String getIP() {
		return socket.getInetAddress().toString().substring(1).trim();
	}
	
	protected int getID() {
		return ID;
	}
	
	protected void setCharacter(Character character) {
		this.character = character;
	}
	
	protected Character getCharacter() {
		return character;
	}


	public void run() {
		System.out.println("Server Thread " + ID + " running.");
		String msg = "";
		while (true) {
			try {
				msg = streamIn.readUTF();
				server.handleIncommingMessage(this, msg);
			} catch (IOException ioe) {
				System.out.println(ID + " ERROR reading: " + ioe.getMessage());
				server.remove(this);
			}
		}
	}

	protected void initiate() throws IOException {
		streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
		streamOut = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
		start();
	}

	@SuppressWarnings("deprecation")
	protected void stopThread() throws IOException {
		if (socket != null)
			socket.close();
		if (streamIn != null)
			streamIn.close();
		if (streamOut != null)
			streamOut.close();

		stop();
	}
}